package org.team4.dao.meta;

import java.util.HashMap;
import java.util.List;

import org.hibernate.SessionFactory;
import org.team4.constants.SQLConstant;
import org.team4.constants.StringConstant;
import org.team4.dao.GenericDAO;
import org.team4.domain.RoleModuleOperate;
import org.team4.domain.RoleUsers;
import org.team4.exception.CRUDException;
import org.team4.util.CacheUtil;
import org.team4.util.Validate;
import org.team4.vo.RoleCache;

import org.team4.dao.meta.RoleModuleOperateDAO;


public class RoleModuleOperateDAO extends GenericDAO<RoleModuleOperate> {

	private static final long serialVersionUID = 9202447484806054849L;
	private static RoleModuleOperateDAO instance;
	
	public static RoleModuleOperateDAO getInstance(SessionFactory sessionFactory) {
        if(instance == null) {
            instance =  new RoleModuleOperateDAO(sessionFactory);
        }
        return instance;
    }
	
    /**
     * 构造函数
     * 
     * @param sessionFactory
     */
    private RoleModuleOperateDAO(SessionFactory sessionFactory) {
        super(sessionFactory, RoleModuleOperate.class);
    }
    
    /**
     * 查找用户的所有操作组件权限
     * 
     * @param ruList
     * @return
     * @throws CRUDException
     */
    public HashMap<String, String> findUsersOperates(List<RoleUsers> ruList, String userId) throws CRUDException {
    	//从缓存中取出现有的权限
    	HashMap<String, String> operates = new HashMap<String, String>();
    	RoleCache roleCache = (RoleCache) CacheUtil.get(RoleCache.CACHE_NAME, userId);
    	if(roleCache != null) {
    		operates = roleCache.getOperate();
    	}
        if (Validate.collectionNotNull(ruList)) {
            for (RoleUsers ru : ruList) {
                List<RoleModuleOperate> roList = this.find(SQLConstant.ROLEOPERATE_BY_ROLEID_HQL, ru.getRole().getId());
                if (Validate.collectionNotNull(roList)) {
                    for (RoleModuleOperate operate : roList) {
                        String useable = operates.get(operate.getWebId());
                        if (Validate.notNull(useable)) {
                            if (StringConstant.FALSE.equals(useable))
                                operates.put(operate.getWebId(), operate.getUseable());
                        } else {
                            operates.put(operate.getWebId(), operate.getUseable());
                        }
                    }
                }
            }
        }
        return operates;
    }

}
